# 用户管理服务层（最小可用实现）
from backend.models.user import User
from backend.infrastructure.database import db

def get_user_list():
    users = User.query.all()
    # 返回所有角色名
    return [
        {
            **u.to_dict(),
            'roles': [role.name for role in u.roles]
        } for u in users
    ]

def create_user(data):
    username = data.get('username')
    password = data.get('password')
    role_names = data.get('roles', ['user'])
    if not username or not password:
        return {'success': False, 'message': '用户名和密码必填'}
    if User.query.filter_by(username=username).first():
        return {'success': False, 'message': '用户名已存在'}
    user = User(username=username)
    user.password = password
    db.session.add(user)
    db.session.commit()
    # 绑定多角色
    from backend.models.role import Role
    from backend.models.user_role import UserRole
    roles = Role.query.filter(Role.name.in_(role_names)).all()
    for r in roles:
        db.session.add(UserRole(user_id=user.id, role_id=r.id))
    db.session.commit()
    return {'success': True, 'data': {**user.to_dict(), 'roles': [r.name for r in roles]}}

def update_user(user_id, data):
    from backend.infrastructure.database import db
    user = db.session.get(User, user_id)
    if not user:
        return {'success': False, 'message': '用户不存在'}
    if 'password' in data:
        user.password = data['password']
    if 'roles' in data:
        from backend.models.role import Role
        from backend.models.user_role import UserRole
        # 先清空原有
        UserRole.query.filter_by(user_id=user.id).delete()
        roles = Role.query.filter(Role.name.in_(data['roles'])).all()
        for r in roles:
            db.session.add(UserRole(user_id=user.id, role_id=r.id))
    if 'status' in data:
        user.status = data['status']
    db.session.commit()
    # 返回最新角色
    roles = [role.name for role in user.roles]
    return {'success': True, 'data': {**user.to_dict(), 'roles': roles}}

def delete_user(user_id):
    from backend.infrastructure.database import db
    user = db.session.get(User, user_id)
    if not user:
        return {'success': False, 'message': '用户不存在'}
    db.session.delete(user)
    db.session.commit()
    return {'success': True, 'message': '用户已删除'}
